<template lang="pug">
div(class="account-bind-weixin")
  template(v-if="bindSuccess")
    i(class="el-icon-success")
    div
      h3 绑定成功

  template(v-else)
    div()
      h3 {{account.name}}
    div(style="padding:10px;")
        el-button(type="primary" @click="bind") 确定绑定
    div(style="padding:10px;")
        el-button(type="text") 关闭页面
</template>

<script>
import dayjs from 'dayjs'
import axios from "@/plugin/axios";
import util from "@/libs/util";

export default {
  data() {
    return {
      account: {},
      bindSuccess: false,
      weixinAuth: { code: null, state: null }
    };
  },
  methods: {
    wxAuthorizition: function(wxInfo) {
      location.href = wxInfo.authorizeUrl;
    },
    tokenLogin: function() {
      const authArgs = this.weixinAuth;
      const options = { url: "token/weixin", data: authArgs, method: "post" };

      var vm = this;
      axios(options)
        .then(tokenInfo => {
          const expiredAt = dayjs().add(tokenInfo.expires - 1, "minute"); // 过期时间
          util.cookies.set("expired", expiredAt.toISOString());
          util.cookies.set("token", tokenInfo.token);
          util.cookies.set("wxuid", tokenInfo.user.id);
          util.cookies.set("avatar", tokenInfo.user.avatar);
          util.cookies.set("nickname", tokenInfo.user.nickname);
          vm.getSimpleAccount();
        })
        .catch(() => {
          // todo: code过期等情况处理
        });
    },
    // 跳转到url
    redirectWxAuth() {
      const prefix = process.env.NODE_ENV !== "development" ? "/" : "/api/";
      const callback_url = encodeURIComponent(location.href);
      location.href = `${prefix}weixinAuth/?callback_url=${callback_url}`;
    },
    getSimpleAccount() {

      const accountId = this.$route.query.accountId;
      const options = {
        url: "admin/account/simpleAccount",
        method: "post",
        data: { accountId }
      };
      const vm = this;
      axios(options)
        .then(account => (vm.account = account))
        .catch(() => {});
    },
    bind() {
      const data = { accountId: this.account.id };
      var options = { url: "admin/account/bindWeixin", method: "post", data: data };
      axios(options)
        .then(() => (this.bindSuccess = true))
        .catch(() => {});
    }
  },
  created: function() {
    const code = util.getQueryString("code");
    const state = util.getQueryString("state");
    this.weixinAuth = {code, state};

    history.replaceState({}, {}, `${location.pathname}${location.hash}`);
    // code和state有值则表示在授权回调
    var next = code && state ? this.tokenLogin : this.redirectWxAuth;
    next();
    // 替换URL参数 只需要pathname和hash 不需要search部分
  }
};
</script>

<style scoped>
.account-bind-weixin {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
